<template>
  <div class="index">
    <div class="dashboardAuth">
      <MyArticleHeader :formData="articleInfo" @submitFn="submit" @cancelFn="cancel"></MyArticleHeader>
    </div>
    <div>
      <form class="layui-form con item">
        <div class="layui-form-item">
          <label class="layui-form-label"><i class="must">*</i>所属计划包</label>
          <div class="layui-inline">
            <select name="planId" v-model="articleInfo.planId" :disabled="id">
              <option value="">请选择</option>
              <option v-for="item in planList" :value="item.planId" :key="item.planId">{{item.name}}</option>
            </select>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label"><i class="must">*</i>标题</label>
          <div class="layui-inline">
            <input type="text" v-model="articleInfo.title" class="layui-input updata" placeholder="请输入文章标题，建议长度不超过30字" lay-verify="required">
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label">摘要</label>
          <div class="layui-input-block">
            <textarea class="layui-textarea abstract" maxlength="300" v-model="articleInfo.summary" text placeholder="请输入摘要，建议长度不超过300字"></textarea>
            <div class="abstract-num"><span num>{{articleInfo.summary.length}}</span><i>/</i><span>300</span></div>
          </div>
        </div>

        <div class="layui-form-item">
          <label class="layui-form-label"><i class="must">*</i>关键字</label>
          <div class="layui-inline">
            <input type="text" class="layui-input updata" name="keyword" v-model="articleInfo.keyword" placeholder="最多可添加5个关键词">
            <span class="rec-tips">（最多5个，以英文状态下“,”隔开，例：外汇,汇率）</span>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label"><i class="must">*</i>标签</label>
          <div class="layui-inline">
            <select name="tagId" v-model="articleInfo.tagId">
              <option value="">请选择</option>
              <option v-for="item in tagList" :value="item.articleTagId" :key="item.articleTagId">{{item.text}}</option>
            </select>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label"><i class="must">*</i>正文</label>
          <div class="layui-input-block">
            <textarea id="edit" style="display: none;" v-model="articleInfo.details"></textarea>
          </div>
        </div>
        <div class="layui-form-item">
          <label class="layui-form-label"><i class="must">*</i>封面图片</label>
          <div class="layui-input-block">
            <div class="layui-inline" v-if="articleInfo.imgUrl">
              <img :src="articleInfo.imgUrl" style="width:182px;height:122px;">
            </div>
            <div class="layui-inline">
              <span class="pic layui-upload-drag" id="up_img">
                <i class="layui-icon"></i>
                <p>点击上传</p>
              </span>
              <span class="tips">尺寸180*120px<br>支持JPG、PNG、GIF图片，1M以内</span>
            </div>
          </div>
        </div>
      </form>
    </div>
    <Footer/>
  </div>
</template>

<script>
import Footer from '@/components/footer'
import MyArticleHeader from '@/components/plan/new-plan-article-header'
import cookie from '@/utils/cookie'
import { getPlanListForAuthor,
  getPlanArticleTagList,
  getPlanArticleInfo,
  updatePlanArticle,
  addPlanArticle,
  uploadUrl } from '@/service/api'
let $ = window.$
export default {
  components: {
    Footer,
    MyArticleHeader
  },
  data () {
    return {
      id: '',
      articleInfo: {
        title: '',
        summary: '',
        keyword: '',
        planId: '',
        tagId: '',
        details: '',
        imgUrl: ''
      },
      tagList: [],
      planList: [],
      layerLoad: null,
      layEditIndex: null,
      submitting: false // 正在提交
    }
  },
  created () {
  },
  mounted () {
    this.$nextTick(() => {
      this.id = this.$route.params.id
      this.showLoadingModal()
      this.initData()
    })
  },
  methods: {
    showLoadingModal () {
      if (window.layer) {
        this.layerLoad = window.layer.load(0, {
          shade: false
        })
      }
    },
    closeLoadingModal () {
      if (window.layer) {
        window.layer.close(this.layerLoad)
      }
    },
    initData () {
      this.showLoadingModal()
      Promise.all([this.getPlanList(), this.getArticleTagList(), this.getArtcleInfo()]).then((res) => {
        let res1 = res[0].data
        if (res1.code === 200) {
          this.planList = res1.data.list
        }
        let res2 = res[1].data
        if (res2.code === 200) {
          this.tagList = res2.data
        } else {
          this.showMsgTip('数据加载失败，请重新加载')
        }
        if (this.id) {
          let res3 = res[2].data
          if (res3.code === 200) {
            // 数据赋值
            let tempData = res3.data
            for (let item in this.articleInfo) {
              this.articleInfo[item] = tempData[item]
            }
            this.articleInfo.articleId = tempData.articleId
          } else {
            this.showMsgTip('数据加载失败，请重新加载')
          }
        }
        this.closeLoadingModal()
        setTimeout(() => {
          this.initLayui()
        }, 500)
      })
    },
    initLayui () {
      window.layui.use(['form', 'layedit', 'upload'], () => {
        var form = window.layui.form
        form.on('select', (data) => {
          this.$set(this.articleInfo, $(data.elem).attr('name'), data.value)
        })
        form.render()
        let upload = window.layui.upload
        let token = cookie.get('device_id')
        upload.render({
          elem: '#up_img',
          url: uploadUrl,
          headers: { accessToken: token },
          size: 1024, // 最大允许上传的文件大小
          before: (obj) => {
          },
          done: (res) => {
            this.articleInfo.imgUrl = res.data.src
          }
        })
        var layedit = window.layui.layedit
        layedit.set({
          uploadImage: {
            url: uploadUrl + `&accessToken=${token}`
          }
        })
        this.layEditIndex = layedit.build('edit')
      })
    },
    cancel () {
      this.$router.go(-1)
    },
    submit () {
      window.layui.use(['layer'], () => {
        if (this.validate()) {
          if (!this.id) {
            this.addNewArticle()
          } else {
            this.updateArticle()
          }
        }
      })
    },
    async addNewArticle () {
      if (this.submitting) {
        this.showMsgTip('内容提交中……')
        return
      }
      this.submitting = true
      this.showLoadingModal()
      let res = await addPlanArticle({...this.articleInfo})
      if (res.status && res.data.code === 200) {
        this.closeLoadingModal()
        this.showMsgTip('添加成功')
        setTimeout(() => {
          this.$router.go(-1)
        }, 500)
      } else {
        this.submitting = false
        this.showMsgTip('添加失败，请重试')
      }
    },
    validate () {
      if (!(this.articleInfo.planId)) {
        this.showMsgTip('请选择所属计划')
        return false
      }
      if (!(this.articleInfo.title && /^.{1,30}$/.test(this.articleInfo.title))) {
        this.showMsgTip('请输入1-30位字符的文章标题')
        return false
      }
      if (!this.articleInfo.summary) {
        this.showMsgTip('请输入摘要内容')
        return false
      }
      if (this.articleInfo.summary.length > 300) {
        this.showMsgTip('摘要内容超长，最多300个字符')
        return false
      }
      let keyword = this.articleInfo.keyword
      if (!keyword) {
        this.showMsgTip('请填写关键字')
        return false
      }
      let tempArr = this.articleInfo.keyword.split(',')
      let resArr = tempArr.filter((item) => item !== '')
      if (resArr.length === 0) {
        this.showMsgTip('请填写关键字')
        return false
      }
      if (resArr.length > 5) {
        this.showMsgTip('关键字最多5个')
        return false
      }
      this.articleInfo.keyword = resArr.join(',')
      if (!(this.articleInfo.tagId)) {
        this.showMsgTip('请选择标签')
        return false
      }
      let detailsWord = window.layui.layedit.getText(this.layEditIndex)
      if (!detailsWord) {
        this.showMsgTip('请填写正文内容')
        return false
      }
      if (detailsWord.length > 50000) {
        this.showMsgTip('正文内容超长，最多50000个字符')
        return false
      }
      this.articleInfo.details = window.layui.layedit.getContent(this.layEditIndex)
      if (!(this.articleInfo.imgUrl)) {
        this.showMsgTip('请上传封面图片')
        return false
      }
      return true
    },
    /**
     * 获取文章的基本信息
     */
    async getArtcleInfo () {
      let res = null
      if (this.id) {
        let obj = {articleId: this.id}
        res = await getPlanArticleInfo(obj)
      }
      return res
    },
    async getPlanList () {
      let searchData = {
        statusText: this.id ? '' : '未结束'
      }
      let res = await getPlanListForAuthor(searchData)
      return res
    },
    async getArticleTagList () {
      let res = await getPlanArticleTagList()
      return res
    },
    async updateArticle () {
      if (this.submitting) {
        this.showMsgTip('内容提交中……')
        return
      }
      this.submitting = true
      this.showLoadingModal()
      delete this.articleInfo.planId
      let res = await updatePlanArticle({...this.articleInfo})
      this.closeLoadingModal()
      if (res.status && res.data.code === 200) {
        this.showMsgTip('更新成功')
        setTimeout(() => {
          this.$router.go(-1)
        }, 500)
      } else {
        this.submitting = false
        this.showMsgTip(`更新失败，${res.data.message}`)
      }
    },
    showMsgTip (msg) {
      window.layui.layer.msg(msg)
    }
  }
}
</script>

<style scoped lang="scss">
@import "../../../style/res/viewpoint";
.layui-input-block {
  margin-left: 135px;
}
.must {
  color: red;
  padding-right: 5px;
}
.con .abstract{
  resize: none;
  width: 430px;
  padding:10px 16px;
  text-align: left;
}
.con .layui-input-block{
  position: relative;
}
.con .abstract-num{
  position: absolute;
  right: 355px;
  bottom: 6px;
  color: #808080;
}
.con .layui-inline .updata{
  text-align: left;
  padding:0 16px;
  width: 360px;
}
.con .layui-inline span {
  line-height: 42px;
}
.layui-inline {
  padding-left: 5px;
}
</style>
